package com.issoft.studentresitor.controller.admin;


import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.issoft.studentresitor.domain.dto.StudentDTO;
import com.issoft.studentresitor.domain.pojo.Registration;
import com.issoft.studentresitor.domain.pojo.Result;
import com.issoft.studentresitor.domain.pojo.Student;
import com.issoft.studentresitor.domain.query.StudentQueryParam;
import com.issoft.studentresitor.domain.vo.StudentVo;
import com.issoft.studentresitor.service.IRegistrationService;
import com.issoft.studentresitor.service.IStudentService;
import com.issoft.studentresitor.utils.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author GJH
 * @since 2025-09-14
 */
@RestController
@RequestMapping("/student")
@Slf4j
@Api(tags = "学生信息")
public class StudentController {
    @Autowired
    private IStudentService studentService;
    @Autowired
    IRegistrationService registrationService;

    /**
     * 分页查询学生信息
     *根据姓名、专业id、联系方式、进行查询
     * 模糊查询：姓名、联系方式
     * @return
     */
    @ApiOperation("分页查询学生信息")
    @GetMapping("/page")
    public Result queryStuPage(@RequestParam(required = false) String name,
                               @RequestParam(required = false) Integer majorId,
                               @RequestParam(required = false) String contactPhone,
                               @RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer pageSize) {

        StudentQueryParam param = new StudentQueryParam();

        param.setName(name);
        param.setMajorId(majorId);
        param.setContactPhone(contactPhone);
        param.setPage(page);
        param.setPageSize(pageSize);

        // 调用service方法
        PageResult<StudentVo> result = studentService.queryStuPage(param);
        return Result.success(result);
    }

    @ApiOperation("删除根据id学生信息")
    @DeleteMapping("{id}")
    public Result delete(@PathVariable Integer id) {
        boolean b = studentService.removeById(id);
        return b ? Result.success() : Result.error("删除失败");
    }
    /**
     * 根据id批量删除学生信息
     * @param ids
     * @return
     */
    @ApiOperation("批量删除学生信息")
    @DeleteMapping("/batchDelete")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        boolean b = studentService.removeByIds(ids);
        return b ? Result.success() : Result.error("批量删除失败");
    }


    @ApiOperation("根据id查询学生信息")
    @GetMapping("{id}")
    public Result get(@PathVariable Integer id) {
        Student student = studentService.getById(id);
        return student != null ? Result.success(student) : Result.error("数据不存在");
    }
    @ApiOperation("添加学生信息")
    @PostMapping
    @Transactional
    public Result add(@RequestBody StudentDTO studentDTO) {
        Student student = new Student();
        BeanUtils.copyProperties(studentDTO, student);

        // 先保存学生信息
        boolean save = studentService.save(student);

        if (save) {
            // 学生学号为：
            String studentId = "20250" + student.getId();
            student.setStudentId(studentId);

            // 更新学生信息，设置学号
            studentService.updateById(student);

            log.info("添加学生信息成功：{}", student);
            String regisid = student.getStudentId();
            log.info("添加注册: " + regisid);
            // INSERT INTO registration (student_id, registration_date) VALUES (?, ?)
            Registration registration = new Registration();
            registration.setStudentId(regisid);
            registration.setRegistrationTime(LocalDateTime.now());
            registration.setEmergencyContact(""); // 设置空字符串作为默认值
            registration.setEmergencyPhone("");
            boolean b = registrationService.save(registration);
            return b ? Result.success() : Result.error("添加失败");
        } else {
            return Result.error("添加学生信息失败");
        }
    }

    @ApiOperation("更新学生信息")
    @PutMapping
    public Result update(@RequestBody StudentDTO studentDTO) {
        Student student = new Student();
        BeanUtils.copyProperties(studentDTO, student);
        boolean update = studentService.updateById(student);
        return update ? Result.success() : Result.error("更新失败");
    }
    @ApiOperation("导出所有文档")
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        try {
            // 执行导出操作
            studentService.export(response);
        } catch (Exception e) {
            log.error("导出学生信息失败", e);
            try {
                // 检查响应是否已提交
                if (!response.isCommitted()) {
                    response.reset();
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write("{\"code\":500,\"message\":\"导出失败:" + e.getMessage() + "\"}");
                    response.getWriter().flush();
                }
            } catch (IOException ioException) {
                log.error("导出失败后的错误处理也失败了", ioException);
            }
        }
    }
    /**
     * 批量导入文档
     * @param file
     * @return
     */
    @ApiOperation("导入文档")
    @PostMapping("/import")
    public Result importExcel(@RequestParam("file") MultipartFile file) {
        // 1. 判断文件是否为空
        if (file == null || file.isEmpty()) {
            return Result.error("上传文件不能为空");
        }

        // 2. 判断文件大小（可选，防止上传过大文件）
        long fileSize = file.getSize();
        if (fileSize > 10 * 1024 * 1024) { // 限制10MB
            return Result.error("文件大小不能超过10MB");
        }

        // 3. 判断文件类型（可选）
        String fileName = file.getOriginalFilename();
        if (fileName != null && !fileName.toLowerCase().endsWith(".xls") && !fileName.toLowerCase().endsWith(".xlsx")) {
            return Result.error("请上传Excel文件（.xls或.xlsx格式）");
        }

        InputStream inputStream = null;
        ExcelReader reader = null;

        try {
            //1.通过file获取输入流
            inputStream = file.getInputStream();
            //读取流
            reader = ExcelUtil.getReader(inputStream);
            List<Student> read = reader.readAll(Student.class);

            // 4. 判断是否有数据
            if (read == null || read.isEmpty()) {
                return Result.error("Excel文件中没有数据");
            }

            // 5. 过滤掉无效数据（可选）
            List<Student> validStudents = read.stream()
                    .filter(student -> student != null &&
                            student.getStudentId() != null &&
                            !student.getStudentId().trim().isEmpty() &&
                            student.getName() != null &&
                            !student.getName().trim().isEmpty())
                    .collect(Collectors.toList());

            if (validStudents.isEmpty()) {
                return Result.error("Excel文件中没有有效的学生数据");
            }

            // 6. 批处理将数据保存到数据库中
            long successCount = 0;
            long failCount = 0;

            for (Student student : validStudents) {
                try {
                    studentService.saveOrUpdate(student);
                    successCount++;
                } catch (Exception e) {
                    log.error("保存学生信息失败，学号：{}，姓名：{}",
                            student.getStudentId(), student.getName(), e);
                    failCount++;
                }
            }

            // 7. 返回结果
            String message = String.format("导入完成，成功%d条，失败%d条", successCount, failCount);
            if (failCount == 0) {
                return Result.success(message);
            } else {
                return Result.error(message);
            }

        } catch (Exception e) {
            log.error("导入学生数据失败", e);
            return Result.error("导入失败：" + e.getMessage());
        } finally {
            // 8. 关闭资源
            if (reader != null) {
                reader.close();
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("关闭输入流失败", e);
                }
            }
        }
    }
    @ApiOperation("查询没有选择班级的人")
    @GetMapping("/noClass")
    public Result queryNoClassStu() {
        List<StudentVo> list = studentService.queryNoClassStu();
        return Result.success(list);
    }
    @ApiOperation("查询没有选择寝室的人")
    @GetMapping("/noDrom")
    public Result queryNoDromStu() {
        List<Student> list = studentService.queryNoDromStu();
        return Result.success(list);
    }
    //查询user_id为空的人
    @ApiOperation("查询user_id为空的人")
    @GetMapping("/noUserId")
    public Result queryNoUserIdStu() {
        List<Student> list = studentService.queryNoUserIdStu();
        return Result.success(list);
    }
    //根据id添加user_id
    @ApiOperation("根据id添加user_id")
    @PutMapping("/addUserId")
    public Result addUserId(@RequestParam(value = "id") Integer id, @RequestParam(value = "userId") Integer userId) {
        int i=studentService.addUserId(id, userId);
        if(i==0)
            return Result.error("添加失败");
        return Result.success("添加成功");
    }
}
